<template>
  <el-card shadow="never" class="aui-card--fill">
    <div class="mod-adx__reporttotal">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
     
          <!-- <el-form-item label="账户">
            <el-select v-model="dataForm.dspId" placeholder="请选择对应的账户" filterable clearable>
              <el-option v-for="item in dspIdList " :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item> -->
               <el-form-item label="账户ID">
          <el-input v-model="dataForm.dspId" placeholder="ID" clearable></el-input>
          </el-form-item>

          <el-form-item label="账户名称">
          <el-input v-model="dataForm.name" placeholder="账户名称" clearable></el-input>
          </el-form-item>
                     <el-form-item label="所属产品" prop="productChannel">
           <el-select v-model="dataForm.productChannel" placeholder="选择运营人员" filterable clearable>
              <el-option v-for="item in productList " :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue">
              </el-option>
            </el-select>
      </el-form-item>
         <el-form-item label="所属媒体" prop="mediaChannel">
         <el-select v-model="dataForm.mediaChannel" placeholder="选择运营人员" filterable clearable>
              <el-option v-for="item in mediaList " :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue">
              </el-option>
            </el-select>
           </el-form-item>

       <el-form-item label="投放起始时间">
          <el-date-picker v-model="dataForm.stime" value-format="yyyy-MM-dd" type="date"
            placeholder="投放起始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="投放结束时间">
          <el-date-picker v-model="dataForm.etime" value-format="yyyy-MM-dd" type="date"
            placeholder="投放结束时间">
          </el-date-picker>
        </el-form-item>


          <el-form-item label="运营负责人">
            <el-select v-model="dataForm.userName" placeholder="选择运营人员" filterable clearable>
              <el-option v-for="item in userNameList " :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="商务">
            <el-select v-model="dataForm.business" placeholder="选择运营人员" filterable clearable>
              <el-option v-for="item in businessList " :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>

        
        <el-form-item>
          <el-button type="primary" @click="getDataList()">{{ $t('query') }}</el-button>
          <el-button style="margin-left: 10px;" @click="showColumnSelector">
            <i class="el-icon-setting"></i> 列设置
          </el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="dataListLoading" :data="dataList" border @selection-change="dataListSelectionChangeHandle" show-summary
        :summary-method="getSummaries"
        style="width: 100%;">
        <el-table-column prop="id" v-if="false" label="主键ID" header-align="center" align="center"></el-table-column>
        <el-table-column v-if="isColumnVisible('date')" prop="date" width="100" label="日期" sortable header-align="center" align="center"></el-table-column>
        <el-table-column :show-overflow-tooltip='true' v-if="false" prop="dspId" label="广告主ID" header-align="center" align="center"></el-table-column>
        <el-table-column v-if="isColumnVisible('name')" width="120" prop="name" label="账户名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="impTotal"   :formatter="caseTypeNumber" label="曝光数量" header-align="center" align="center"></el-table-column>
        <el-table-column v-if="isColumnVisible('cpcTotal')" prop="cpcTotal"  :formatter="caseTypeNumber" label="点击数量" header-align="center" align="center"></el-table-column>
        <el-table-column v-if="isColumnVisible('radis')" prop="radis" width="150" label="点击转化率" header-align="center" align="center">
          <template slot-scope="scope">
            {{ ratio(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column v-if="isColumnVisible('act')" prop="act" width="150px"  sortable :formatter="caseTypeNumber" label="实际激活数" header-align="center" align="center"></el-table-column>
        <el-table-column v-if="isColumnVisible('totalAct')" prop="totalAct" width="150px"  sortable label="总激活数" header-align="center" align="center">
          <template slot-scope="scope">
            {{ totalActNumber(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column v-if="isColumnVisible('register')" prop="register" width="150px" :formatter="caseTypeNumber" sortable label="实际注册数" header-align="center" align="center"></el-table-column>
        <el-table-column v-if="isColumnVisible('totalRegister')" prop="totalRegister" width="150px" sortable label="总注册数" header-align="center" align="center">
          <template slot-scope="scope">
            {{ totalRegisterNumber(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column v-if="isColumnVisible('pay')" prop="pay" width="150px"  :formatter="caseTypeNumber" sortable label="实际付费数" header-align="center" align="center"></el-table-column>
        <el-table-column v-if="isColumnVisible('totalPay')" prop="totalPay" width="150px"  sortable label="总付费数" header-align="center" align="center">
          <template slot-scope="scope">
            {{ totalPayNumber(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column v-if="isColumnVisible('retain')" prop="retain" width="150px"  :formatter="caseTypeNumber" sortable label="实际次留数" header-align="center" align="center"></el-table-column>
        <el-table-column v-if="isColumnVisible('totalRetain')" prop="totalRetain" width="150px"  sortable label="总次留数" header-align="center" align="center">
          <template slot-scope="scope">
            {{ totalRetainNumber(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column v-if="isColumnVisible('wakeup')" prop="wakeup" width="150px"  :formatter="caseTypeNumber" sortable label="实际唤醒数" header-align="center" align="center"></el-table-column>
        <el-table-column v-if="isColumnVisible('totalWakeup')" prop="totalWakeup" width="150px"  sortable label="总唤醒数" header-align="center" align="center">
          <template slot-scope="scope">
            {{ totalWakeupNumber(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column v-if="isColumnVisible('keybehaviors')" prop="keybehaviors" width="150px"  :formatter="caseTypeNumber" sortable label="关键行为" header-align="center" align="center"></el-table-column>
        <el-table-column v-if="isColumnVisible('totalKeybehaviors')" prop="totalKeybehaviors" width="150px"  sortable label="总关键行为" header-align="center" align="center">
          <template slot-scope="scope">
            {{ totalKeybehaviorsNumber(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column v-if="isColumnVisible('userName')" prop="userName"  label="所属运营" header-align="center" align="center"></el-table-column>
        <el-table-column v-if="isColumnVisible('business')" prop="business"  label="所属商务" header-align="center" align="center"></el-table-column>
      
      
        <!-- <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="100">
          <template slot-scope="scope">
            <el-button  type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">录入消耗</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <el-pagination :current-page="page" :page-sizes="[10, 20, 50, 100]" :page-size="limit" :total="total"
        layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeHandle"
        @current-change="pageCurrentChangeHandle">
      </el-pagination>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

      <!-- 列设置弹窗 -->
      <el-dialog title="列设置" :visible.sync="columnSelectorVisible" width="400px">
        <el-checkbox-group v-model="selectedColumns">
          <el-checkbox v-for="col in availableColumns" :key="col.prop" :label="col.prop">
            {{ col.label }}
          </el-checkbox>
        </el-checkbox-group>
        <span slot="footer" class="dialog-footer">
          <el-button @click="columnSelectorVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleColumnSelectorConfirm">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import AddOrUpdate from './reporttotal-add-or-update'
import { getDictDataList } from '@/utils'

export default {
  mixins: [mixinViewModule],
  data() {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '/adx/reporttotal/ocpxTotal',
        getDataListIsPage: true,
        exportURL: '/adx/reporttotal/export',
        deleteURL: '/adx/reporttotal',
        deleteIsBatch: true
      },
      columnSelectorVisible: false,
      selectedColumns: ['date', 'name', 'cpcTotal', 'radis', 'act', 'register', 'pay', 'retain', 'wakeup', 'keybehaviors', 'userName', 'business'],
      availableColumns: [
        { prop: 'date', label: '日期' },
        { prop: 'name', label: '账户名称' },
        { prop: 'cpcTotal', label: '点击数量' },
        { prop: 'radis', label: '点击转化率' },
        { prop: 'act', label: '实际激活数' },
        { prop: 'totalAct', label: '总激活数' },
        { prop: 'register', label: '实际注册数' },
        { prop: 'totalRegister', label: '总注册数' },
        { prop: 'pay', label: '实际付费数' },
        { prop: 'totalPay', label: '总付费数' },
        { prop: 'retain', label: '实际次留数' },
        { prop: 'totalRetain', label: '总次留数' },
        { prop: 'wakeup', label: '实际唤醒数' },
        { prop: 'totalWakeup', label: '总唤醒数' },
        { prop: 'keybehaviors', label: '关键行为' },
        { prop: 'totalKeybehaviors', label: '总关键行为' },
        { prop: 'userName', label: '所属运营' },
        { prop: 'business', label: '所属商务' }
      ],
      dspIdList: [],
      userNameList: [],
      businessList:[],
      isAgeVisible: false,
      mediaList:[],
      productList:[],
      dataForm: {
        id: '',
        stime: '',
        etime: '',
      },
      summaryData: {} // 存储从后端返回的汇总数据
    }
  },
  mounted() {
    // 从本地存储加载列设置
    const savedColumns = localStorage.getItem('ocpxReportColumns')
    if (savedColumns) {
      this.selectedColumns = JSON.parse(savedColumns)
    }
    
    this.getDspIdDict();
    this.getNameDict();
    this.getBusinessDict();
    this.getProductList();
    this.getMediaList();
  },
  components: {
    AddOrUpdate
  },
  computed: {

  },
  methods: {
    // 显示列选择器
    showColumnSelector() {
      this.columnSelectorVisible = true
    },

    // 确认列选择
    handleColumnSelectorConfirm() {
      this.columnSelectorVisible = false
      // 保存到本地存储，以便下次打开页面时保持选择状态
      localStorage.setItem('ocpxReportColumns', JSON.stringify(this.selectedColumns))
    },

    // 判断列是否显示
    isColumnVisible(prop) {
      return this.selectedColumns.includes(prop)
    },

    // 覆盖 mixin 的 query 方法，接收后端返回的汇总数据
    query() {
      this.dataListLoading = true
      this.$http.get(
        this.mixinViewModuleOptions.getDataListURL,
        {
          params: {
            order: this.order,
            orderField: this.orderField,
            page: this.mixinViewModuleOptions.getDataListIsPage ? this.page : null,
            limit: this.mixinViewModuleOptions.getDataListIsPage ? this.limit : null,
            ...this.dataForm
          }
        }
      ).then(({ data: res }) => {
        this.dataListLoading = false
        if (res.code !== 0) {
          this.dataList = []
          this.total = 0
          this.summaryData = {}
          return this.$message.error(res.msg)
        }
        this.dataList = this.mixinViewModuleOptions.getDataListIsPage ? res.data.list : res.data
        this.total = this.mixinViewModuleOptions.getDataListIsPage ? res.data.total : 0
        // 接收后端返回的汇总数据
        this.summaryData = res.data.summary || {}
      }).catch(() => {
        this.dataListLoading = false
      })
    },
    getDspIdDict() {
      this.dspIdList = getDictDataList("dspIdList")

    },
   getMediaList() {
      this.mediaList = getDictDataList("mediaList")
    },
       getProductList() {
      this.productList = getDictDataList("productList")
    },
    luuu(){
       alert("正在开发中.....")
    },
    caseTypeNumber(row, column, cellValue){
          // 检查单元格的值是否为0，如果是，则返回"/"
      if (cellValue === '0') {
        return '/';
      }
      // 否则返回原始的单元格值
      return cellValue;
    },

    capitalizeFirstLetter(str) {
      if (!str) return str; // 如果字符串为空，直接返回
      return str.replace(/^./, (match) => match.toUpperCase());
    },
    totalActNumber(row, column, cellValue) {
    // 计算总激活数 = 实际激活数 + 过滤激活数
    const act = Number(row.act) || 0;
    const filterAct = Number(row.filterAct) || 0;
    
    // 如果两个值都为0，返回"/"
    if (act === 0 && filterAct === 0) {
      return '/';
    }
    
    // 返回总和
    return act + filterAct;
  },

  totalRegisterNumber(row, column, cellValue) {
    // 计算总注册数 = 实际注册数 + 过滤注册数
    const register = Number(row.register) || 0;
    const filterRegister = Number(row.filterRegister) || 0;
    
    // 如果两个值都为0，返回"/"
    if (register === 0 && filterRegister === 0) {
      return '/';
    }
    
    // 返回总和
    return register + filterRegister;
  },

  //总付费
  totalPayNumber(row, column, cellValue) {
    // 计算总付费数 = 实际付费数 + 过滤付费数
    const pay = Number(row.pay) || 0;
    const filterPay = Number(row.filterPay) || 0;
    
    // 如果两个值都为0，返回"/"
    if (pay === 0 && filterPay === 0) {
      return '/';
    }
    
    // 返回总和
    return pay + filterPay;
  },

  //总次留
  totalRetainNumber(row, column, cellValue) {
    // 计算总次留数 = 实际次留数 + 过滤次留数
    const retain = Number(row.retain) || 0;
    const filterRetain = Number(row.filterRetain) || 0;
    
    // 如果两个值都为0，返回"/"
    if (retain === 0 && filterRetain === 0) {
      return '/';
    }
    
    // 返回总和
    return retain + filterRetain;
  },

  //总唤醒
  totalWakeupNumber(row, column, cellValue) {
    // 计算总唤醒数 = 实际唤醒数 + 过滤唤醒数
    const wakeup = Number(row.wakeup) || 0;
    const filterWakeup = Number(row.filterWakeup) || 0;
    
    // 如果两个值都为0，返回"/"
    if (wakeup === 0 && filterWakeup === 0) {
      return '/';
    }
    
    // 返回总和
    return wakeup + filterWakeup;
  },

  //总关键行为
  totalKeybehaviorsNumber(row, column, cellValue) {
    // 计算总关键行为 = 实际关键行为 + 过滤关键行为
    const keybehaviors = Number(row.keybehaviors) || 0;
    const filterKeybehaviors = Number(row.filterKeybehaviors) || 0;
    
    // 如果两个值都为0，返回"/"
    if (keybehaviors === 0 && filterKeybehaviors === 0) {
      return '/';
    }
    
    // 返回总和
    return keybehaviors + filterKeybehaviors;
  },
 

    getNameDict() {
      this.userNameList = getDictDataList("userNameList")

    },
    getBusinessDict() {
      this.businessList = getDictDataList("businessList")

    },
    ratio(data) {
        let numericResultTypeTotal =0;
        let act= Number(data.act);
        let register= Number(data.register);
        let pay= Number(data.pay);
        let wakeup= Number(data.wakeup);
      if(act!=0){
        console.log("act")
        numericResultTypeTotal=Number(act);
      }else if(register!=0){
         console.log("register")
        numericResultTypeTotal=Number(register);
        console.log(numericResultTypeTotal)
      }else if(pay!=0){
         console.log("pay")
        numericResultTypeTotal=pay;
      }else if(wakeup!=0){
         console.log("wakeup")
        numericResultTypeTotal=wakeup;
      }else{
          console.log("empty")
        numericResultTypeTotal=0;
      }

      
     
      const numericClickTotal = Number(data.cpcTotal);

      if (numericClickTotal === 0) {
        return 0;
      }
      const result = (numericResultTypeTotal / numericClickTotal).toFixed(4);
      return (result * 100).toFixed(2) + '%';
    },
    getSummaries(param) {
      const { columns } = param;
      const sums = [];
      
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }

        const prop = column.property;

        // 从后端返回的汇总数据中获取值
        if (this.summaryData && this.summaryData[prop] !== undefined && this.summaryData[prop] !== null) {
          const value = this.summaryData[prop];
          // 如果值为 0 或 '0'，显示 '/'
          if (value === 0 || value === '0') {
            sums[index] = '/';
          } else {
            sums[index] = value;
          }
        } else {
          // 如果后端没有返回该字段的汇总，显示空
          sums[index] = '';
        }
      });
      
      return sums;
    }
  }
}
</script>
